import os
import shutil
import hashlib
import configparser
import time
import subprocess
import requests
from pathlib import Path
from time import sleep
import datetime
import signal
import logging

logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# handler = logging.FileHandler("log.txt")
# handler.setLevel(logging.INFO)
# handler.setFormatter(formatter)
# logger.addHandler(handler)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(console)

#视频处理准备类，对于视频的内容进行关键帧提取， 并分离出音频文件，都保存在tmpath的临时目录中，供http访问；
class prepare:
    def __init__(self):

        current_file_path=os.path.dirname(os.path.abspath(__file__))
        print(current_file_path)
        config = configparser.ConfigParser()
        config.read(current_file_path+"/conf/config.ini")
        #该目录定义在config.ini中做为截图的临时路径，处理完成后可以删除，只做为临时处理时使用；
        # self.tmpath = config.get("frame", "tmpath") 
        # self.domain = config.get("frame", "domain")
        return

    #下载视频文件；
    def download(self, wpath, url, tid):
        #首先下载到本地进行截图的处理；
        tmp_str = wpath +str(tid)
        tmp_path = Path(tmp_str)
        tmp_path.mkdir(parents=True, exist_ok=True)
        ext = os.path.splitext(url)[-1]

        tmp_file = tmp_str + "/"+str(tid)+str(ext)
        leng = 1
        logger.info(tmp_file+'->开始下载')
        while(leng==1):
            torrent=requests.get(url)
            leng=len(list(torrent.iter_content(1024)))  #下载区块数
            if(leng==1):								#如果是1 就是空文件 重新下载
                sleep(1)
                logger.error(tmp_file+'->下载文件错误，退出!')
                raise RuntimeError('下载文件错误')
            else:
                logger.info(tmp_file+'->下载完成')

        with open(tmp_file,'wb') as f:				
            for chunk in torrent.iter_content(1024):	#防止文件过大，以1024为单位一段段写入
                f.write(chunk)
        return tmp_str, tmp_file

    #生成关键帧图片，调用qkframe来进行关键帧的提取；
    def qkframe(self, path, file):

        timeout = 600
        logger.info(file+"->开始截图...")
        #首先下载到本地进行截图的处理；

        start = datetime.datetime.now()
        process = subprocess.Popen(["qkframe", "300", file, path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.communicate()
        logger.info(file+"->结束截图...")
        return

    #删除下载的文件；
    def rmDWfile(self, file_path):

        os.unlink(file_path)
        return

if  __name__ == "__main__":
        kf = prepare()
        t1 = time.time()
        try:
            for i in range(1,51):
                tpath, tfile = kf.download("http://10.0.2.8/ts/news/"+str(i)+".mp4", str(i))
                kf.qkframe(tpath, tfile)
                kf.rmDWfile(tfile)
            logger.info("共用时->"+str(time.time()-t1)+"秒")
        except Exception:
            logger.error('抛出自定义NameError异常')
            raise
